package com.qdlc.p2p.biz.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.UserStatisticsService;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dao.UserDao;
import com.qdlc.p2p.dal.dao.UserStatisticsDao;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserStatistics;
import com.qdlc.p2p.dal.util.UserTypeUtils;

@Service
public class UserStatisticsServiceImpl implements UserStatisticsService {

    @Resource
    private UserStatisticsDao userStatisticsDao;

    @Resource
    private UserDao userDao;

    @Override
    public void init(User user) {
        UserStatistics userStatistics = new UserStatistics();
        userStatistics.setBorrowCount(0L);
        userStatistics.setInvestCount(0L);
        userStatistics.setUser(user);
        userStatisticsDao.merge(userStatistics);
    }

    @Override
    public void doExcute(User user) {
        QueryParam arg0 = QueryParam.getInstance();
        arg0.addParam("user", user.getUserId());
        List<UserStatistics> list = userStatisticsDao.findByCriteria(arg0);


        user = userDao.find(user.getUserId());
        if (list.isEmpty()) {
            UserStatistics userStatistics = new UserStatistics();
            if (UserTypeUtils.isBorrower(user.getUserId())) { // 借款人
                userStatistics.setBorrowCount(1L);
                userStatistics.setInvestCount(0L);
            } else if (UserTypeUtils.isInvestor(user.getUserId())) {// 投资人
                userStatistics.setBorrowCount(0L);
                userStatistics.setInvestCount(1L);
            }
            userStatistics.setUser(user);
            userStatisticsDao.save(userStatistics);
        } else {
            UserStatistics userStatistics = list.get(0);
            if (UserTypeUtils.isBorrower(user.getUserId())) { // 借款人
                userStatistics.setBorrowCount(userStatistics.getBorrowCount() + 1);
            } else if (UserTypeUtils.isInvestor(user.getUserId())) {// 投资人
                userStatistics.setInvestCount(userStatistics.getInvestCount() + 1);
            }
            userStatisticsDao.update(userStatistics);
        }


    }

}
